﻿using Furion.DynamicApiController;
using Furion.FriendlyException;
using GoodAdmin.Core;
using GoodAdmin.System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace GoodAdmin.AuthExtra;

/// <summary>
/// 认证服务
/// </summary>
[ApiDescriptionSettings("System", Tag = "认证服务")]
[Route("/ding/auth")]
public class DingLoginService(DingUserService dingdingUserService,IAuthService authService) : IDynamicApiController
{
    private readonly DingUserService dingdingUserService = dingdingUserService;
    private readonly IAuthService authService = authService;

    [HttpPost("dingLogin")]
    [AllowAnonymous]
    public async Task<LoginOutput> Login(DingLoginInput input)
    {
        if (string.IsNullOrWhiteSpace(input.AuthCode))
        {
            throw Oops.Bah("未获取到钉钉授权码");
        }
        var dingUserId = await dingdingUserService.GetDingdingUserIdByAuthCode(input.AuthCode);
        //查找用户信息根据需要修改       
        var sysUser = await DbContext.Db.Queryable<SysUser>().FirstAsync(it => it.WorkId == dingUserId && it.Status == CommonConst.STATUS_ENABLE);
        if (sysUser == null)
        {
            var dingUser = await dingdingUserService.GetDingdingUserDetail(dingUserId);
            if (dingUser == null)
            {
                throw Oops.Bah("未查询到人员信息，请联系管理员");
            }
        }          
        var loginInfo = await authService.LoginToken(sysUser);
        return loginInfo;
    }
}
